package resources;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequencer;
import javax.sound.midi.Sequence;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.InvalidMidiDataException;

/** Background music. */
public enum Music {
    BACKGROUND_1("Shop3.mid"),
    MAIN_MENU("Trial.mid");

    /** The currently playing music. */
    private static Music nowPlaying;
    /** */
    private static Sequencer sequencer;

    static {
        try {
            sequencer = MidiSystem.getSequencer();
            sequencer.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);
            sequencer.open();
        } catch (MidiUnavailableException e) {
            e.printStackTrace();
        }
    }

    /** */
    private final String filename;
    /** */
    private Sequence sequence;

    /** @param newFilename - the filename. */
    private Music(final String newFilename) {
        filename = newFilename;
    }

    /** @return the filename. */
    public String getFilename() {
        return filename;
    }

    /** @return the sequence. */
    public Sequence getSequence() {
        return sequence;
    }

    /** Loads all the music in this enumeration. */
    public static void loadAll() {
        for (Music m : values()) {
            try {
                URL url = Sprite.class.getResource("/music/" + m.filename);
                System.out.println("Loading music: " + url);
                m.sequence = MidiSystem.getSequence(url);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (InvalidMidiDataException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /** @param music - the music to play or null to stop the music. */
    public static void set(final Music music) {
        if (nowPlaying == music) {
            return;
        }
        if (nowPlaying != null) {
            sequencer.stop();
        }
        nowPlaying = music;
        if (nowPlaying != null) {
            try {
                sequencer.setSequence(nowPlaying.sequence);
            } catch (InvalidMidiDataException e) {
                e.printStackTrace();
            }
            sequencer.setMicrosecondPosition(0);
            sequencer.start();
        }
    }
}
